package com.group.voting_system.controller;

import com.group.voting_system.service.IVoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author: xyf
 * @Date: 2019/4/28 22:57
 */
@Controller
public class DataController {

    @Autowired
    IVoteService voteService;

    @Value("${localExcel.download}")
    String download;

    @GetMapping("/data/{vid}")
    public void statistics(@PathVariable("vid") Integer vid,
                           HttpServletResponse response) {

        voteService.downloadStatistics(vid);
        File file = new File(download + "\\" + vid + ".xls");
        if (file.exists()){
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + vid + ".xls");// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream out = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    out.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
